<template>
  <div class="owner-pre-store">
    <section class="header">
      <a-page-header title="租客预存" @back="goBack"/>
    </section>
    <section class="content">
      <a-card class="card">
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane key="preStoreSetting" :tab="TAB_MAP.preStoreSetting">
            <a-table
                :title="(data) => TAB_MAP.preStoreSetting + '列表'"
                :columns="PS_SETTING_TABLE_COLUMNS"
                :loading="dataLoading"
                :pagination="psSettingPagination"
                :dataSource="villageSettingList"
                @change="handlePSSettingChange"
                rowKey="id"
            >
              <template
                  #customFilterDropdown="{
                  setSelectedKeys,
                  selectedKeys,
                  confirm,
                  clearFilters,
                  column,
                }"
              >
                <!-- 搜索用户名称 -->
                <template v-if="column.key === 'village_name'">
                  <div style="padding: 8px">
                    <a-input
                        ref="searchInput"
                        placeholder="搜索所属项目"
                        v-model:value="keyword"
                        style="width: 188px; margin-bottom: 8px; display: block"
                        @pressEnter="preStoreVillageSearch(selectedKeys, confirm)"
                    />
                    <a-button
                        type="primary"
                        size="small"
                        style="width: 90px; margin-right: 8px"
                        @click="preStoreVillageSearch(selectedKeys, confirm)"
                    >
                      <template #icon>
                        <SearchOutlined/>
                      </template>
                      搜索
                    </a-button>
                    <a-button
                        size="small"
                        style="width: 90px"
                        @click="preStoreVillagerReset(clearFilters, confirm)"
                    >
                      重置
                    </a-button>
                  </div>
                </template>
              </template>
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'status'">
                  <a-switch
                      :checked="text"
                      checked-children="开"
                      un-checked-children="关"
                      :checked-value="1"
                      :un-checked-value="0"
                      @change="(val) => handleVillageStatusChange(val, record.id)"
                  />
                </template>
                <template v-if="column.key=='can_customize'">
                  <a-tag :color="record.can_customize == 1 ? 'green' : 'red' ">
                    {{ record.can_customize == 1 ? '开启' : '关闭' }}
                  </a-tag>
                </template>
                <template v-if="column.key === 'cost_types'">
                  <span v-if="text && text.length">
                    <a-tag
                        v-for="(item, index) of text"
                        :key="index"
                        color="blue"
                        style="margin-bottom: 12px"
                    >
                      {{ item }}
                    </a-tag>
                  </span>
                  <span v-else>--</span>
                </template>
                <template v-if="column.key === 'recharge_item'">
                  <span v-if="text && text.length">
                    <a-tag
                        v-for="item of text"
                        :key="item"
                        color="cyan"
                    >
                      {{ item }}
                    </a-tag>
                  </span>
                  <span v-else>--</span>
                </template>
                <template v-if="column.key === 'action'">
                  <a-button type="link" @click="onPSSettingEdit(text)">
                    编辑
                  </a-button>
                </template>
              </template>
              <template #customFilterIcon>
                <search-outlined :style="{ color: '#108ee9' }"/>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="preStoreRecord" :tab="TAB_MAP.preStoreRecord">
            <a-table
                :title="(data) => TAB_MAP.preStoreRecord + '列表'"
                :dataSource="ownerPrestoreList"
                :columns="PS_RECORD_TABLE_COLUMNS"
                :loading="storeRecordLoading"
                :pagination="psRecordPagination"
                @change="handlePSStoreRecordChange"
                :scroll="{ x: 'max-content' }"
                rowKey="id"
            >
              <template
                  #customFilterDropdown="{
                  setSelectedKeys,
                  selectedKeys,
                  confirm,
                  clearFilters,
                  column,
                }"
              >
                <!-- 搜索用户名称 -->
                <template v-if="column.key === 'cuser_name'">
                  <div style="padding: 8px">
                    <a-input
                        ref="searchInput"
                        placeholder="搜索用户名称"
                        v-model:value="cuser_name"
                        style="width: 188px; margin-bottom: 8px; display: block"
                        @pressEnter="handleUserSearch(selectedKeys, confirm)"
                    />
                    <a-button
                        type="primary"
                        size="small"
                        style="width: 90px; margin-right: 8px"
                        @click="handleUserSearch(selectedKeys, confirm)"
                    >
                      <template #icon>
                        <SearchOutlined/>
                      </template>
                      搜索
                    </a-button>

                    <a-button
                        size="small"
                        style="width: 90px"
                        @click="handleUserReset(clearFilters, confirm)"
                    >
                      重置
                    </a-button>
                  </div>
                </template>
                <!-- 搜索项目名称 -->
                <template v-if="column.key === 'village_name'">
                  <div style="padding: 8px">
                    <a-input
                        ref="searchInput"
                        placeholder="搜索项目名称"
                        v-model:value="village_name"
                        style="width: 188px; margin-bottom: 8px; display: block"
                        @pressEnter="handleVillageSearch(selectedKeys, confirm)"
                    />
                    <a-button
                        type="primary"
                        size="small"
                        style="width: 90px; margin-right: 8px"
                        @click="handleVillageSearch(selectedKeys, confirm)"
                    >
                      <template #icon>
                        <SearchOutlined/>
                      </template>
                      搜索
                    </a-button>
                    <a-button
                        size="small"
                        style="width: 90px"
                        @click="handleVillageReset(clearFilters, confirm)"
                    >
                      重置
                    </a-button>
                  </div>
                </template>
              </template>
              <template #customFilterIcon="{ filtered, column }">
                <template
                    v-if="
                    column.key == 'cuser_name' || column.key == 'village_name'
                  "
                >
                  <search-outlined
                      :style="{ color: filtered ? '#108ee9' : undefined }"
                  />
                </template>
                <template v-else>
                  <filter-filled/>
                </template>
              </template>
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'single_type_txt'">
                  <span style="color: #5973e2" v-if="text"
                  >专项-{{ text }}</span
                  >
                  <span v-else>非专项预存</span>
                </template>
                <template v-if="column.key === 'action'">
                  <a-button type="link" @click="onTurnover(record.stream_id)">
                    查看流水
                  </a-button>
                </template>
              </template>
            </a-table>
          </a-tab-pane>

        </a-tabs>
      </a-card>
    </section>

    <!-- 预存款设置 编辑项目 -->
    <PreStoreSettingEdit
        :visible="psSettingState.editVisible"
        :id="psSettingState.currentId"
        @cancel="psSettingState.editVisible = false"
        @success="handlePSSettingEdit"
    />

  </div>
</template>

<script>
import {defineComponent, reactive, toRefs, computed} from "vue";
import {useRouter} from "vue-router";
import PreStoreSettingEdit from "./modules/PreStoreSettingEdit.vue";
import request from "../../../common/utils/request";
import {message} from "ant-design-vue";
import {PaySetting} from "bl-common-vue3";
import {SearchOutlined, FilterFilled} from "@ant-design/icons-vue";

export default defineComponent({
  name: "OwnerPreStore",
  components: {PreStoreSettingEdit, SearchOutlined, FilterFilled},
  setup() {
    const router = useRouter();
    const state = reactive({
      activeKey: "preStoreSetting",
      dataLoading: false,

      // 预存项设置
      psSettingState: {
        page: 1,
        pageSize: 10,
        total: 0,
        currentId: 0,
        editVisible: false,
      },
      villageSettingList: [],


      // 预存记录
      ownerPrestoreList: [],
      psStoreRecord: {
        page: 1,
        pageSize: 20,
        total: 0,
        order_status: undefined,
        pay_method: undefined,
        single_type_txt: [],
      },
      storeRecordLoading: false,
      cuser_name: "",
      village_name: "",
      payMethod: [],
      orderStatus: [],
      streamConfig: [],
      keyword: "",
    });

    /** 启动、关闭项目预存项 */
    const handleVillageStatusChange = (status, id) => {
      request
          .put("/org", "/streamPrestore/makeStatus", {
            status,
            id,
            needMsg: true,
          })
          .then((res) => {
            message.success(res.msg || "修改成功！");
            getVillagePSSetingInfo();
          });
    };

    /** 编辑预存项设置 */
    const onPSSettingEdit = (id) => {
      state.psSettingState.currentId = id;
      state.psSettingState.editVisible = true;
    };
    const handlePSSettingEdit = () => {
      state.psSettingState.editVisible = false;
      getVillagePSSetingInfo();
    };

    /** 获取预存项设置 */
    const getVillagePSSetingInfo = (init = false) => {
      state.dataLoading = true;
      if (init) {
        state.psSettingState.page = 1;
        state.psSettingState.pageSize = 10;
      }
      const params = {
        page: state.psSettingState.page,
        limit: state.psSettingState.pageSize,
      };
      if (state.keyword) {
        params.keyword = state.keyword;
      }
      request
          .get("/org", "/stream/villagePrestoreList", params)
          .then((res) => {
            state.villageSettingList = res.list;
            state.psSettingState.total = res.total
          })
          .finally(() => {
            state.dataLoading = false;
          });
    };
    const psSettingPagination = computed(() => ({
      current: state.psSettingState.page,
      pageSize: state.psSettingState.pageSize,
      total: state.psSettingState.total,
      showSizeChanger: true,
      showTotal: (total) => `共${total}条`,
    }));
    const handlePSSettingChange = (pager, filters, sorter) => {
      state.psSettingState.page = pager.current;
      state.psSettingState.pageSize = pager.pageSize;
      getVillagePSSetingInfo();
    };

    // 搜索所属项目
    const preStoreVillageSearch = (selectedKeys, confirm) => {
      confirm();
      getVillagePSSetingInfo(true);
    };
    const preStoreVillagerReset = (clearFilters, confirm) => {
      clearFilters();
      state.keyword = "";
      confirm();
      getVillagePSSetingInfo(true);
    };

    const psRecordPagination = computed(() => ({
      current: state.psStoreRecord.page,
      pageSize: state.psStoreRecord.pageSize,
      total: state.psStoreRecord.total,
      showSizeChanger: true,
      showTotal: (total) => `共${total}条`,
    }));

    const handlePSStoreRecordChange = (pager, filters, sorter) => {
      console.log(filters.single_type_txt, "1111");
      state.psStoreRecord.page = pager.current;
      state.psStoreRecord.pageSize = pager.pageSize;
      state.psStoreRecord.order_status = filters.status_txt;
      state.psStoreRecord.single_type_txt = filters.single_type_txt;
      state.psStoreRecord.pay_method = filters.pay_method_txt;
      if (filters.status_txt || filters.pay_method_txt) {
        state.psStoreRecord.page = 1;
        state.psStoreRecord.pageSize = 20;
      }
      getOwnerPrestoreList();
    };

    // 筛选项
    const getListinit = () => {
      request.get("/org", "/streamPrestore/listInit").then((res) => {
        state.orderStatus = res.initData.orderStatus.map((item) => {
          return {
            text: item.name,
            value: item.key,
          };
        });
        state.payMethod = res.initData.payMethod.map((item) => {
          return {
            text: item.name,
            value: item.key,
          };
        });
        state.streamConfig = res.initData.streamConfig.map((item) => {
          return {
            text: item.name,
            value: item.key,
          };
        });
      });
    };

    const PS_RECORD_TABLE_COLUMNS = computed(() => {
      let orderList = state.orderStatus;
      let payMethodList = state.payMethod;
      let streamConfig = state.streamConfig;
      console.log("orderList", orderList);
      console.log("payMethodList", payMethodList);
      console.log("streamConfig", streamConfig);
      return [
        {
          title: "用户名称",
          dataIndex: "cuser_name",
          key: "cuser_name",
          width: 300,
          customFilterDropdown: true,
        },
        {
          title: "项目名称",
          dataIndex: "village_name",
          key: "village_name",
          width: 300,
          customFilterDropdown: true,
        },
        {
          title: "专项预存",
          dataIndex: "single_type_txt",
          key: "single_type_txt",
          filters: streamConfig.length ? streamConfig : [],
          width: 200,
        },
        {
          title: "订单金额",
          dataIndex: "pay_money",
          width: 200,
        },
        {
          title: "订单状态",
          dataIndex: "status_txt",
          filters: orderList.length ? orderList : [],
          width: 150,
        },
        {
          title: "支付时间",
          dataIndex: "pay_time",
          width: 150,
        },
        {
          title: "支付方式",
          dataIndex: "pay_method_txt",
          filters: payMethodList.length ? payMethodList : [],
          width: 150,
        },
        {
          title: "第三方订单号",
          dataIndex: "third_order_no",
          width: 300,
        },
        {
          title: "操作",
          dataIndex: "id",
          key: "action",
          fixed: "right",
          width: 150,
        },
      ];
    });

    const defaultPagination = () => {
      state.psStoreRecord.page = 1;
      state.psStoreRecord.pageSize = 20;
      state.psStoreRecord.total = 0;
    };

    // 搜索用户姓名
    const handleUserSearch = (selectedKeys, confirm) => {
      defaultPagination();
      getOwnerPrestoreList();
      confirm();
    };
    const handleUserReset = (clearFilters, confirm) => {
      clearFilters();
      defaultPagination();
      getOwnerPrestoreList();
      confirm();
    };

    // 搜索项目
    const handleVillageSearch = (selectedKeys, confirm) => {
      defaultPagination();
      getOwnerPrestoreList();
      confirm();
    };

    const handleVillageReset = (clearFilters, confirm) => {
      clearFilters();
      confirm();
      defaultPagination();
      getOwnerPrestoreList();
    };

    // 查看流水
    const onTurnover = (tId) => {
      router.push({name: "turnoverDetail", query: {tId}});
    };

    // 获取预留记录
    const getOwnerPrestoreList = () => {
      let params = {
        page: state.psStoreRecord.page,
        limit: state.psStoreRecord.pageSize,
      };
      if (state.psStoreRecord.order_status) {
        params.order_status = state.psStoreRecord.order_status;
      }
      if (state.psStoreRecord.single_type_txt) {
        params.single_type = state.psStoreRecord.single_type_txt;
      }
      if (state.psStoreRecord.pay_method) {
        params.pay_method = state.psStoreRecord.pay_method;
      }
      if (state.cuser_name) {
        params.cuser_name = state.cuser_name;
      }
      if (state.village_name) {
        params.village_name = state.village_name;
      }
      state.storeRecordLoading = true;
      request.get("/org", "/stream/ownerPrestoreList", params).then((res) => {
        state.ownerPrestoreList = res.list;
        state.psStoreRecord.total = res.total;
        state.storeRecordLoading = false;
      });
    };

    /** 初始化 */
    const init = () => {
      getVillagePSSetingInfo();
      getOwnerPrestoreList();
      getListinit();
    };

    /** 返回 */
    const goBack = () => {
      if (window.history.state.back) {
        router.back();
      } else {
        router.replace("streamList");
      }
    };

    init();

    return {
      TAB_MAP,
      PS_SETTING_TABLE_COLUMNS,
      psSettingPagination,

      ...toRefs(state),
      goBack,
      handlePSSettingChange,
      onPSSettingEdit,
      handlePSSettingEdit,
      handleVillageStatusChange,

      onTurnover,
      psRecordPagination,
      handlePSStoreRecordChange,
      PS_RECORD_TABLE_COLUMNS,
      handleUserSearch,
      handleUserReset,
      handleVillageReset,
      handleVillageSearch,

      preStoreVillageSearch,
      preStoreVillagerReset,
    };
  },
});
const TAB_MAP = {
  preStoreSetting: "预存项设置",
  // paySetting: "支付设置",
  preStoreRecord: "预存记录",
};
const PS_SETTING_TABLE_COLUMNS = [
  {
    title: "所属项目",
    dataIndex: "village_name",
    key: "village_name",
    width: 300,
    customFilterDropdown: true,
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: 150,
  },
  {
    title: "开启自定义金额充值",
    key: "can_customize",
  },

  // {
  //   title: "自动缴费项目",
  //   dataIndex: "cost_types_txt",
  //   key: "cost_types",
  //   width: 300,
  // },
  // {
  //   title: "可选充值项",
  //   dataIndex: "recharge_item",
  //   key: "recharge_item",
  //   width: 300,
  // },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
  },
];
</script>

<style lang="less" scoped>
.owner-pre-store {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    height: 50px;
    background: #fff;

    &:deep(.ant-page-header) {
      padding: 10px 20px;
    }
  }

  .content {
    margin-top: 10px;
    flex: 1;
    padding: 10px;
    overflow-y: auto;

    .card {
      height: 100%;
    }
  }
}
</style>
